import { Module } from 'vuex'
import { IRootState } from '../types'
import { IConfigDefState, INode, IModuleConfigdef } from './types'
import handleModel from '@/render/utils/modelTree'

import {
  updateModuleConfigDef,
  getModuleConfigDef
} from '@/render/service/configdef/configdef'

const configdefModule: Module<IConfigDefState, IRootState> = {
  namespaced: true,
  state() {
    return {
      moduleConfigdefs: new Map<string, IModuleConfigdef>()
    }
  },
  getters: {
    getModuleConfigDef: (state, { projectName, projectModuleName }) => {
      if (state.moduleConfigdefs != null) {
        if (state.moduleConfigdefs.has(`${projectName}_${projectModuleName}`)) {
          return state.moduleConfigdefs.get(
            `${projectName}_${projectModuleName}`
          )
        }
      }
    }
  },
  mutations: {
    SET_MODULECONFIGDEF(state, { projectName, projectModuleName, model }) {
      if (state.moduleConfigdefs == null) {
        state.moduleConfigdefs = new Map()
      }
      state.moduleConfigdefs.set(`${projectName}_${projectModuleName}`, model)
    }
  },
  actions: {
    loadModuleConfigDef({ commit, state }, value) {
      return new Promise((resolve, reject) => {
        if (
          state.moduleConfigdefs &&
          state.moduleConfigdefs.size > 0 &&
          state.moduleConfigdefs.has(
            `${value.projectName}_${value.projectModuleName}`
          )
        ) {
          resolve(
            state.moduleConfigdefs.get(
              `${value.projectName}_${value.projectModuleName}`
            )
          )
        } else {
          getModuleConfigDef(value.projectName, value.projectModuleName)
            .then((res: any) => {
              const data = res.data?.module

              console.log(data)

              const module = handleModel(data)

              commit('SET_MODULECONFIGDEF', {
                projectName: value.projectName,
                projectModuleName: value.projectModuleName,
                model: module
              })
              resolve(module)
            })
            .catch((error: Error) => {
              console.log('ajax请求失败')
              reject(error)
            })
        }
      })
    },
    updateModuleConfigDef({ commit, state }, value) {
      return new Promise((resolve, reject) => {
        updateModuleConfigDef(value)
          .then((res: any) => {
            commit('SET_MODULECONFIGDEF', {
              projectName: value.projectName,
              projectModuleName: value.projectModuleName,
              model: value.module
            })
            resolve(res)
          })
          .catch((error: any) => {
            reject(error)
          })
        // console.log(value)
        // resolve('success')
      })
    }
  }
}

export default configdefModule
